package com.main.ok.lucene.mysql;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

/**
 * 
 * @Type SearchDoc
 * @Desc
 * @author Administrator
 * @date 2015年3月16日
 * @Version V1.0
 */
public class SearchDoc {
    private static final String indexPath = "g:/lucene";
    private static DirectoryReader reader = null;

    public static void main(String[] args) throws IOException, ParseException {
        // String field = "app_id";
        // String target = "p_ios_weiyi";
        // String field = "content";
        // String target = "接收方的ID是：12121397";
        // search(field, target);
        searchPageAfter("CKL", 1, 10);
    }

    public static void search(String field, Object target) throws IOException, ParseException {
        IndexSearcher search = getSearcher();

        Analyzer ana = new StandardAnalyzer();
        QueryParser paser = new QueryParser(field, ana);
        Query query = paser.parse(target.toString());

        TopDocs docs = search.search(query, 100);

        System.out.println("all hits:" + docs.totalHits);
        int docId = docs.scoreDocs[0].doc;
        Document result = search.doc(docId);
        System.out.println(result.get("memo") + "-" + result.get("content") + "-" + result.get("gmt_created"));
    }

    /**
     * 分页获取 查询
     * 
     * @param query
     * @param pageIndex
     * @param pageSize
     */
    public static void searchPageAfter(String query, int pageIndex, int pageSize) {
        IndexSearcher searcher = getSearcher();
        QueryParser parse = new QueryParser("content", new StandardAnalyzer());
        Query q = null;
        try {
            q = parse.parse(query);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            ScoreDoc lastSd = getLastScoreDoc(pageIndex, pageSize, q, searcher);
            TopDocs docs = searcher.searchAfter(lastSd, q, pageSize);
            System.out.println(docs.totalHits);
            for (ScoreDoc sd : docs.scoreDocs) {
                Document document = searcher.doc(sd.doc);
                System.out.println(document.get("id") + "--" + document.get("memo"));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 根据页码和分页大小获取上一次的最后一个ScoreDoc
     */
    private static ScoreDoc getLastScoreDoc(int pageIndex, int pageSize, Query query, IndexSearcher searcher) throws IOException {
        if (pageIndex == 1)
            return null;// 如果是第一页就返回空
        int num = pageSize * (pageIndex - 1);// 获取上一页的数量
        TopDocs tds = searcher.search(query, num);
        return tds.scoreDocs[num - 1];
    }

    /**
     * 
     * @return
     */
    private static IndexSearcher getSearcher() {
        FSDirectory directory = null;
        try {
            directory = FSDirectory.open(Paths.get(indexPath));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            if (reader == null) {
                reader = DirectoryReader.open(directory);
            } else {
                DirectoryReader tr = DirectoryReader.openIfChanged(reader);
                if (tr != null) {
                    reader.close();
                    reader = tr;
                }
            }
            return new IndexSearcher(reader);
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
